#!/usr/bin/env python

# override the default reporting of coords

import warnings
warnings.filterwarnings("ignore")
import pylab as pl
#from numpy import mean,histogram,arange
import scipy.stats as ssts
import scipy.optimize as sop
from scipy import linspace, array, log, arange
import sys

import mpl_toolkits.mplot3d as p3
import matplotlib.pyplot as plt

#from matplotlib import *

dbfile = sys.argv[1]
f = open(dbfile,"r")
counter = 0
x = []
y = []
z = []
coo = {}
for line in f:
    counter += 1
    if counter == 5:
        things = line.split("|")
        for t in range(len(things)):
            things[t] = things[t].strip()
    if counter >= 7 and not line.startswith("["):
        coords = line.split(" ")
        for i in range(len(coords)):
            if i not in coo:
                coo[i] = []
            if coords[i] != "\n":
                #print coords[i]
                coo[i].append(float(coords[i]))

x = coo[0]
y = coo[2]
z = coo[4]
#xmean = max(x)
#for i in range(len(x)):
#    x[i] = x[i]/xmean
#ymean = max(y)
#for i in range(len(y)):
#    y[i] = y[i]/ymean

color = ['b','g','r','c','m','y','k','w']
#ax = subplot(111)
leg=[]
dimensions = range(1,len(coo)-1)
#dimensions = [116]

fig = plt.figure()
ax = p3.Axes3D(fig)
xss = {}
yss = {}
nss = {}
proms = {}
for i in dimensions:
	if sum(coo[i]) != 0:
		fk = ssts.gaussian_kde(coo[i])
		xk = linspace(min(coo[i]),max(coo[i]),len(coo[i]))
		yk = fk.evaluate(xk)
		vls = array(coo[i])
	
		def funcion(x,p):
			return fk.integrate_box_1d(min(coo[i]),x) - p
	
		x0 = sop.fsolve(funcion,vls.mean()-vls.std(),args=(0.13))
		x1 = sop.fsolve(funcion,vls.mean()+vls.std(),args=(0.87))
	

		#print "-->",i,len(coo[i])
		#print x0,fk.integrate_box_1d(min(coo[i]),x0)
		#print x1,fk.integrate_box_1d(min(coo[i]),x1)
		
		
		ar = array(coo[i])	
		#fn = ssts.norm(ar.mean(),ar.std())
		fn = ssts.norm(ar.mean(),ar.std())
		yn = fn.pdf(xk)
	
	
		#print coo[i]
		#*l2 = pl.hist(coo[i],bins=len(coo[i]),histtype='step',normed=True, ec='green',ls='dotted')
		#l2 = pl.hist(coo[i],bins=len(coo[i]),histtype='step',normed=False, ec='#BFBFBF',ls='dotted')
		#l4 = pl.plot(xk,yk,'red')
		xss[i] = xk
		yss[i] = yk
		nss[i] = yn
		key = max(yk)
		#key = xk.mean()
		if key not in proms:
			proms[key] = []
		proms[key].append(i)
	else:
		print "-->",i
	
pr = proms.keys()
pr.sort()
j = 0
for p in pr:
	for i in proms[p]:
		#print i
		ax.plot(xss[i], yss[i], zs=j, zdir='y', color="b", alpha=0.3)
		#ax.plot(xss[i], nss[i], zs=j, zdir='y', color="r", alpha=0.3)
		j+=1
	
	#*l5 = pl.plot(xk,yn,'blue')
	#*pl.axvline(x0, color="black",lw=0.1)
	#*pl.axvline(x1, color="black",lw=0.1)
	#*pl.axvline(pl.array(coo[i]).mean(), color="black",lw=1)
	#leg.append(str(i))
#ax.legend()
    #h1,bins1 = histogram(x,bins=10)
    
#plot(bins1[1:],h1,marker="o",color="blue",ls="--")
#ax.fmt_ydata = millions
#semilogy(x,y,marker='s',ls='none',nonposy='clip',color="green")
#for i in range(len(things)):
#    ax.text(x[i],y[i],things[i],transform=ax.transData,fontsize="8")

pl.savefig("figura.eps")
pl.show()
